<template>
    <div>
        <div style="margin-top: 20px; width: 100%">
            <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                <div class="query-row">
                    <el-form-item label="退货单编号">
                        <el-input v-model="page.returnNumber" />
                    </el-form-item>
                    <el-form-item label="退货单名称" style="margin-left: -20px">
                        <el-input v-model="page.returnName" />
                    </el-form-item>
                    <el-form-item label="生产工单" style="margin-left: 20px">
                        <el-input v-model="page.productionwork" />
                    </el-form-item>
                </div>
                <div class="query-row">
                    <el-form-item label="退料类型" style="margin-left: 20px">
                        <el-select v-model="page.returntype" placeholder="请选择单据状态" size="large" filterable>
                            <el-option label="余料退料" :value="1" checked />
                            <el-option label="坏料退料" :value="2" />
                            <el-option label="废料退料" :value="3" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">查询</el-button>
                    <el-button type="primary" @click="empty">清空</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="width: 100px">
            <el-button type="primary" @click="AddInfo()">新增</el-button>
        </div>

        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="returnNumber" label="退料单编号" />
            <el-table-column prop="returnName" label="退料单名称" />
            <el-table-column prop="returntype" label="退料类型">
                <template #default="scope">
                    <span v-if="scope.row.returntype === 1">余料退料</span>
                    <span v-else-if="scope.row.returntype === 2">坏料退料</span>
                    <span v-else-if="scope.row.returntype === 3">废料退料</span>
                </template>
            </el-table-column>
            <el-table-column prop="productionwork" label="生产工单" />
            <el-table-column prop="workstation" label="工作站" />
            <el-table-column prop="returnTime" label="退料日期" />
            <el-table-column prop="documentStatus" label="单据状态">
                <template #default="scope">
                    <span v-if="scope.row.documentStatus === 0">草稿</span>
                    <span v-else-if="scope.row.documentStatus === 1">待上架</span>
                    <span v-else-if="scope.row.documentStatus === 2">已上架</span>
                    <span v-else-if="scope.row.documentStatus === 3">已取消</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button size="small" @click="DelFrom(scope.row.pId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div>
            <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>


    <div>
        <el-dialog v-model="dialogFormVisible" title="添加生产报工" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <div style="display: flex; flex-wrap: wrap;">
                    <!-- 第一排，两条数据 -->
                    <el-form-item label="退料单编号" prop="returnNumber" style="flex: 0 0 50%; max-width: 50%;">
                        <el-input v-model="ruleForm.returnNumber" autocomplete="off" style="width: 180px; height: 30px"
                            :readonly="ruleForm.autoGenerate" clearable @click.native="handleCodeClick" />
                        <template slot="prepend">R</template>
                        <el-switch width="40" v-model="ruleForm.autoGenerate" active-text="自动生成" active-color="#67C23A"
                            @change="handleSwitchChange" />
                    </el-form-item>
                    <el-form-item label="退料单名称" prop="returnName" style="flex: 0 0 50%; max-width: 50%;">
                        <el-input v-model="ruleForm.returnName" />
                    </el-form-item>
                    <!-- 第二排，三条数据 -->
                    <el-form-item label="退料单类型" prop="returntype" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-select v-model="ruleForm.returntype" placeholder="请选择单据状态" size="large" filterable>
                            <el-option label="余料退料" :value="1" />
                            <el-option label="坏料退料" :value="2" />
                            <el-option label="废料退料" :value="3" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生产工单" prop="productionwork" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productionwork" />
                        <el-button type="primary" @click="product()">生产工单</el-button>
                    </el-form-item>
                    <el-form-item label="退料日期" prop="returnTime" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-date-picker v-model="ruleForm.returnTime" type="datetime"
                            placeholder="Select date and time" />
                    </el-form-item>
                    <!-- 备注单独一排 -->
                    <el-form-item label="备注" prop="remark" style="width: 100%;">
                        <el-input v-model="ruleForm.remark" type="textarea" />
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="AddForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <div>
        <el-dialog v-model="dialogFormVisible3" title="显示生产工单" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="工单编号" style="margin-left: 30px">
                        <el-input v-model="page3.workOrderCoding" />
                    </el-form-item>
                    <el-form-item label="工单名称" style="margin-left: 20px">
                        <el-input v-model="page3.workOrderName" />
                    </el-form-item>
                    <el-form-item label="产品编号" style="margin-left: 20px">
                        <el-input v-model="page3.productNumber" />
                    </el-form-item>
                    <el-form-item label="产品名称" style="margin-left: 20px">
                        <el-input v-model="page3.productName" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page3.customerNamwe" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData3">查询</el-button>
                        <el-button type="primary" @click="empty3">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData2" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="workOrderCoding" label="工单编号" />
                <el-table-column prop="workOrderName" label="工单名称" />
                <el-table-column prop="workOrderType" label="工单来源" />
                <el-table-column prop="orderNumber" label="订单编号" />
                <el-table-column prop="productNumber" label="产品编号" />
                <el-table-column prop="productName" label="产品名称" />
                <el-table-column prop="specifications" label="规格型号" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="customerCode" label="客户编码" />
                <el-table-column prop="customerNamwe" label="客户名称" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page3.index" v-model:page-size="page3.size"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page3.totalCount" @size-change="handleSizeChange3" @current-change="handleCurrentChang3" />
            </div>
            <el-button type="primary" @click="AddGongdan()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible3 = false">取消</el-button>
        </el-dialog>

    </div>
</template>
<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination } from 'element-plus';
import { onMounted, ref, reactive, computed } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData = ref([]);
const tableData2 = ref([]);
const dialogFormVisible = ref(false);
const dialogFormVisible3 = ref(false);

const product = () => {
    dialogFormVisible3.value = true;
    fetchData3();
}

// 查询表单数据
const page3 = reactive({
    index: 1,
    size: 10,
    totalCount: 0,
    totalPage: 0,
    workOrderCoding: '',
    workOrderName: '',
    productNumber: '',
    productName: '',
    customerNamwe: '',
});

// 整合生产工单、查询和分页的方法
const fetchData3 = () => {
    axios.get(apiUrl+'/T5/WorkOrder/GetWorkOrder', { params: page3 })
        .then((res) => {
            tableData2.value = res.data.data;
            page3.totalCount = res.data.totalCount;
            page3.totalPage = res.data.totalPage;
        })
};
const handleSizeChange3 = (val: number) => {
    console.log(`${val} items per page`);
    page3.size = val;
    fetchData3();
};
const handleCurrentChang3 = (val: number) => {
    console.log(`current page: ${val}`);
    page3.index = val;
    fetchData3();
};
const empty3 = () => {
    page3.workOrderCoding = '';
    page3.workOrderName = '';
    page3.productNumber = '';
    page3.productName = '';
    page3.customerNamwe = '';
    fetchData3();
};

const selectedRow = ref(); // 用于存储选中的行
const AddGongdan = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('WorkOrder', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('WorkOrder'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible3.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('WorkOrder');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.workOrderCoding) {
            // 将 taskName 反填到生产任务字段
            ruleForm.productionwork = task.workOrderCoding;
            console.log('生产任务字段已反填:', ruleForm.productionwork);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

// 查询表单数据
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    returnNumber: '',
    returnName: '',
    returntype: '',
    productionwork: '',
});

// 整合显示生产任务、查询和分页的方法
const fetchData = () => {
    axios.get(apiUrl + "/T5/ProductInfo/GetProductionreturn", { params: page })
        .then((res) => {
            tableData.value = res.data.data;
            page.totalCount = res.data.totalCount;
            page.totalPage = res.data.totalPage;
        })
};
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    page.PageSize = val;
    fetchData();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    page.PageIndex = val;
    fetchData();
};
const empty = () => {
    page.returnNumber = '';
    page.returnName = '';
    page.returntype = '';
    page.productionwork = '';
    fetchData();
};

//逻辑删除生产报工
const DelFrom = (pId: any) => {
    axios.put(apiUrl +'/T6/ProductInfos/DelProductionreturn', { pId: pId })
        .then((res) => {
            if (res.data.code == 204) {
                ElMessage({
                    message: res.data.msg,
                    type: 'success',
                })
                fetchData();
            } else {
                ElMessage({
                    message: '删除失败',
                    type: 'error',
                })
            }
        })
}

const AddInfo = () => {
    dialogFormVisible.value = true;
    // 初始化 ruleForm
    ruleForm.pId = 0;
    ruleForm.returnNumber = '';
    ruleForm.returnName = '';
    ruleForm.returntype = null;
    ruleForm.productionwork = '';
    ruleForm.workstation = '';
    ruleForm.returnTime = new Date();
    ruleForm.documentStatus = 0;
    ruleForm.remark = '';
    ruleForm.isDelete = false;
};

const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
    pId: 0,
    returnNumber: '',
    returnName: '',
    returntype: null,
    productionwork: '',
    workstation: '',
    returnTime: new Date(),
    documentStatus: null,
    remark: '',
    isDelete: false,
    autoGenerate: false, // 是否自动生成
});

// 生成生产退料编号（GYLX+时间戳）
const generateCode = () => {
    const timestamp = new Date().toISOString().replace(/[-:TZ]/g, "").substring(0, 14); // 获取精确到毫秒的时间戳
    ruleForm.returnNumber = `SCTL${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
    ruleForm.autoGenerate = val;
    if (val) {
        generateCode(); // 开启自动生成时立即生成
    } else {
        ruleForm.returnNumber = ""; // 关闭时清空编号
    }
};

const handleCodeClick = () => {
    if (ruleForm.autoGenerate) {
        generateCode(); // 点击输入框时重新生成
    }
};

const AddForm = async (formEl: FormInstance | undefined) => {
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);
            axios.post(apiUrl +'/T6/ProductInfos/AddProductionreturn', ruleForm)
                .then(res => {
                    if (res.data.code == 100) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false;
                        fetchData();
                    } else {
                        ElMessage.error("添加失败!");
                    }
                });
        } else {
            console.log('error submit!', fields);
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));

onMounted(() => {
    fetchData();
});
</script>
<style></style>